<template>
  <div class="extract">
    <van-nav-bar
      title="AI核保助务"
      left-text="返回"
      fixed
      placeholder
      left-arrow
      @click-left="onClickLeft"
    />
    <div class="picbox">
      <!-- <p class="cf-title">
        *请确认图片里<span style="color: #e60012">{{params.itemsName}}</span
        >的文字内容部分完整
      </p> -->
      <p class="cf-title">
        * 请确认图片里体检报告文字内容是完整的
      </p>
      <div class="img-box">
        <img :src="imgSrc" alt="" />
      </div>
      <!-- <div class="img-box">
        <img :src="imgSrcTest" alt="" />
      </div> -->
    </div>

    <!-- <div class="subjectbox">
      <div class="title">
        <span></span>
        <p>&nbsp;您想要分析哪个体检项目</p>
      </div>
      <div class="selectbox">
        <van-cell is-link title="选择体检项目" @click="show = true" />
        <van-action-sheet v-model="show" :actions="actions" @select="onSelect" />
      </div>
      <div class="tagbox">
        <span>{{Project}}</span>
      </div>
    </div> -->

    <!-- <div class="subjectbox">
      <div class="title">
        <span></span>
        <p>&nbsp;您想要分析哪个体检项目</p>
      </div> -->
    <!-- <div class="selectbox"> -->
    <!-- <div class="selectbox-content" @click="show = true">
          <span>选择体检项目</span>
          <div>
            <span>{{Project}}</span>
            <van-icon name="arrow" color="#99999" />
          </div>
        </div> -->
    <!-- <van-cell is-link title="选择体检项目" @click="show = true" /> -->
    <!-- <van-action-sheet v-model="show" :actions="actions" @select="onSelect" /> -->
    <!-- </div> -->
    <!-- <div class="tagbox">
        <span v-for="(item, index) in actions" :key="index">{{
          item.name
        }}</span>
      </div>
    </div> -->

    <div class="btnbox">
      <div class="btn1" @click="anewClk">重拍</div>
      <div v-if="submitBtm" class="btn2" @click="ocrClk">提交分析</div>
      <div v-else class="btn3">提交分析</div>
    </div>
  </div>
</template>

<script>
import { recognizeApi , identifyingApi } from "@/api/requestApi"; //调接口
// import casePng from "@/assets/img/case.png"
export default {
  name: "extract",
  components: {},
  data() {
    return {
      anewBtn:true,//控制重拍按钮
      params:{},
      show: false,
      actions: [
        { name: "肝部彩超" },
        { name: "甲状腺彩超" },
        { name: "静息心电图" },
        { name: "胸部X光片" },
      ],
      imgSrc: "",
      Project: "",
      submitBtm:true,
      identifyingNo:"",
      healthPropertyId:'',
    };
  },
  created(){
    this.anewBtn = true;
    // 获取路由参数
    if(this.$route.params.photoData){
      this.params = this.$route.params.photoData;
      console.log('从$route中的this.params.selectId',this.params.selectId);
      sessionStorage.setItem("orcParam",JSON.stringify(this.params))
    }else{
      let orcParam = JSON.parse(sessionStorage.getItem("orcParam"))
      console.log('点击了返回按钮从session中拿orcParam!!!')
      if(orcParam){
        this.params = orcParam;
      }
    }
    if(this.params.selectId && this.params.selectId.length > 0){
      let selectIdList = this.params.selectId;
      for (let i = 0; i < selectIdList.length; i++) {
      let newHealthPropertyId = ""
      for (let i = 0; i < selectIdList.length; i++) {
        newHealthPropertyId += 'healthPropertyId='+ selectIdList[i] + '&'
      }
      this.healthPropertyId = newHealthPropertyId.slice(0,-1);
      }
    }
    console.log("this.healthPropertyId",this.healthPropertyId);
  },
  mounted() {
    this.getIdentifyingFn();
    // let blobToFile1 = this.base64ImgtoFile(this.imgSrcTest);
    // let blobToFile = this.dataURLtoBlobFn(this.imgSrcTest);
    // let blobToFile2 = this.blobToFileFn(blobToFile,'blobToFile');
    // console.log('blobToFile1',blobToFile1);
    // console.log('blobToFile',blobToFile);
    // console.log('blobToFile2',blobToFile2);
    this.$nextTick(()=>{
        // this.imgSrc = 'data:image/jpg;base64,'+ this.params.Base64Img;
				this.imgSrc = this.params.Base64Img;
    })

  },

  methods: {
    onClickLeft() {
      this.$router.go(-1);
    },

    onSelect(item) {
      // 默认情况下点击选项时不会自动收起
      // 可以通过 close-on-click-action 属性开启自动收起
      this.show = false;
      this.Project = item.name;
      //this.$toast(item.name);
    },

    anewClk() {
      if(this.anewBtn){
        this.$router.push({ path: "/consult" });
      }
    },

    // 获取标识
    getIdentifyingFn(){
      identifyingApi().then((res) => {
        this.$store.commit('loading/SET_LOADING',false);
        if (res.data.resultCode == 0) {
          this.identifyingNo = res.data.data;
        }
      }).catch((err) => {
          console.log(err);
          this.$store.commit('loading/SET_LOADING',false);
      });
    },

    // 提交分析
    ocrClk() {
      this.anewBtn = false;
      this.submitBtm = false;
      this.$store.commit('loading/SET_LOADING',true);
      // let blobToFile = this.dataURLtoBlobFn(this.imgSrc);
      // let blobToJpg = this.blobToJpeg(blobToFile);
      let blobToFile = this.base64ImgtoFile(this.imgSrc,"blob");
      let fd = new FormData();
      fd.append("imageFile", blobToFile);
      fd.append("itemsCode", this.params.itemsCode);
      fd.append("identifying", this.identifyingNo);
      console.log('identifying',this.identifyingNo);
      fd.append("pictureType",  this.params.openFromGallery? 2 : 1);
      fd.append("healthPropertyIds", JSON.stringify(this.params.selectId));
      console.log('healthPropertyIds',this.params.selectId);
      recognizeApi(fd).then((res) => {
        this.$store.commit('loading/SET_LOADING',false);
        if (res.data.resultCode == 0) {
          sessionStorage.setItem('taskNo',res.data.data.taskNo);
          setTimeout(() => {
            let newParams = { Base64Img:this.imgSrc }
            this.$router.push({name: 'report', params: { photoData: newParams } })
          }, 1000);
        }else{
          this.$toast(res.data.resultMsg || "失败");
          this.submitBtm = true;
          this.getIdentifyingFn();
          this.$store.commit('loading/SET_LOADING',false);
        }
      }).catch((err) => {
          this.$toast(res.data.resultMsg || "失败");
          this.$store.commit('loading/SET_LOADING',false);
          this.submitBtm = true;
      });
      if (false) {
          this.$dialog.confirm({
            title: '请裁剪体检报告的文字范围',
            message: '',
          })
            .then(() => {

            })
            .catch(() => {
            });
          }
    },

    base64ImgtoFile(dataurl, filename) {
      const arr = dataurl.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const suffix = mime.split('/')[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime
      })
    },

    //将base64转换为blob
    dataURLtoBlobFn(dataurl) {
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },

    //将blob转换为file
    blobToFileFn(theBlob, fileName) {
      theBlob.lastModifiedDate = new Date();
      theBlob.name = fileName;
      return theBlob;
    },


    blobToJpeg(blob, callback) {
    // 创建一个用于绘制的canvas元素
      var canvas = document.createElement('canvas');
      var ctx = canvas.getContext('2d');
    
      // 将blob转为img，并在图片加载完成后进行转换
      var img = new Image();
      img.onload = function() {
        // 设置canvas的宽高
        canvas.width = img.width;
        canvas.height = img.height;
    
        // 在canvas上绘制图片
        ctx.drawImage(img, 0, 0);
    
        // 将canvas的内容转为jpg格式的Blob
         canvas.toBlob(function(blob) {
          callback(blob); // 调用回调函数，传递转换后的jpg Blob
        }, 'image/jpg', 1.0); // 1.0是图片质量，可以根据需要调整
      };
    
      // 将Blob转为对象URL，用于创建Image对象
      var url = URL.createObjectURL(blob);
      img.src = url;
      return img
    },


    
    // 生成UUID
    makeUuid(len, radix) {
      const chars =
        "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(
          ""
        );
      let uuid = [],
        i;
      radix = radix || chars.length;
      if (len) {
        for (let i = 0; i < len; i++)
          uuid[i] = chars[0 | (Math.random() * radix)];
      } else {
        let r;
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
        uuid[14] = "4";
        for (let i = 0; i < 36; i++) {
          if (!uuid[i]) {
            r = 0 | (Math.random() * 16);
            uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
          }
        }
      }
      return uuid.join("");
    },
  },
};
</script>

<style scoped>
.extract {
  margin: 0 10px;
  background-color: #f6f6f6;
  font-size: 14px;
  height: 100vh;
}
.picbox {
  padding: 10px;
  /* background-color: #fff; */
}
.picbox .cf-title {
  text-align: center;
  line-height: 40px;
  height: 40px;
  margin: 0 -10px 2vh;
  /* color: #999; */
  background-color: #fff;
  text-align: left;
  font-weight: 500;
}
.img-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 32vh;
  padding: 0 5vw;
  background-color: #fff;
  border-radius: 10px;
}

.picbox img {
  height: 23vh;
  width: 100%;
  object-fit: contain;
  border: 1px solid #ccc;
}

.subjectbox {
  height: 200px;
  background-color: #fff;
  margin: 14px;
  padding: 10px 6px;
}

.subjectbox .title {
  display: flex;
}
.subjectbox .title span {
  width: 5px;
  height: 20px;
  background-color: #fea247;
}

.subjectbox p {
  text-align: left;
  line-height: 20px;
  height: 20px;
}

.subjectbox .selectbox {
  margin: 14px 10px;
  border: 1px solid #999;
  border-radius: 4px;
}

.subjectbox .selectbox .selectbox-content {
  padding: 0 6px;
  height: 40px;
  line-height: 40px;
  display: flex;
  justify-content: space-between;
}

.subjectbox .tagbox {
  display: flex;
  flex-wrap: wrap-reverse;
  justify-content: space-around;
}

.subjectbox .tagbox span {
  margin-top: 10px;
  padding: 4px;
  color: #999;
  background-color: #f2f2f2;
}

.btnbox {
  display: flex;
  justify-content: space-around;
  margin: 20px 5vw 0;

}

.btnbox div {
  width: 180px;
  height: 40px;
  line-height: 40px;

}

.btnbox .btn1 {
  background-color: #fff;
  border: 1px solid #eb3433;
  color: #eb3433;
  border-radius: 6px;
  margin-right: 3vw;
}

.btnbox .btn2 {
  background-color: #eb3433;
  border: 1px solid #eb3433;
  color: #fff;
  border-radius: 6px;
}

.btnbox .btn3 {
  background-color: #e05050;
  border: 1px solid #e05050;
  color: #fff;
  border-radius: 6px;
}
</style>
